import Toast from "@vant/weapp/toast/toast";
import { saveProfile, getProfile } from "../../apis/user";
import { serverUrl } from "../../config/env";
const app = getApp();
const defaultAvatarUrl =
  "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0";

Page({
  data: {
    userInfo: {
      avatarUrl: "",
      nickName: "",
    },
    uploadUrl: "",
    canIUseGetUserProfile: wx.canIUse("getUserProfile"),
    canIUseNicknameComp: wx.canIUse("input.type.nickname"),
  },
  async saveInfo() {
    const that = this;
    if (this.data.uploadUrl) {
      // 改头像了
      wx.uploadFile({
        url: serverUrl + "/file/img", //仅为示例，非真实的接口地址
        filePath: this.data.uploadUrl,
        name: "file",
        header: {
          token: wx.getStorageSync("token"),
        },
        formData: {
          path: "avatar",
          isCompress: 1,
        },
        async success(res) {
          const { nickName } = that.data.userInfo;
          console.log(res.data);

          if (res.data) {
            const obj = JSON.parse(res.data);
            if (obj.code === 0) {
              await saveProfile({
                name: nickName,
                headUrl: obj.data,
              });
              Toast.success("保存成功");
            }
          }
        },
      });
    } else {
      const { nickName } = that.data.userInfo;
      // 没改头像
      await saveProfile({
        name: nickName,
      });
      Toast.success("保存成功");
    }
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail;
    this.setData({
      uploadUrl: avatarUrl,
    });
  },
  onInputChange(e) {
    const nickName = e.detail.value;
    const { avatarUrl } = this.data.userInfo;
    this.setData({
      "userInfo.nickName": nickName,
    });
  },
  async getInfo() {
    const res = await getProfile();
    console.log(res);

    this.setData({
      "userInfo.nickName": res.name || "未命名",
      "userInfo.avatarUrl": res.headUrl || defaultAvatarUrl,
    });
  },
  onLoad() {
    this.getInfo();
  },
});
